package com.shenganyuan.smac.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;

import com.oklib.utils.helper.RxUtil;
import com.oklib.utils.network.http.ViseHttp;
import com.oklib.utils.network.http.callback.ACallback;
import com.oklib.utils.network.http.subscriber.ApiCallbackSubscriber;
import com.oklib.utils.pref.AnyPref;
import com.oklib.utils.view.ToastUtils;
import com.oklib.widget.dialog.ConfirmDialog;
import com.shenganyuan.smac.App;
import com.shenganyuan.smac.R;
import com.shenganyuan.smac.common.Config;
import com.shenganyuan.smac.common.beans.APILoginParam;
import com.shenganyuan.smac.common.beans.ApiLoginUser;
import com.shenganyuan.smac.common.data.Api;
import com.shenganyuan.smac.common.view.launcher.LauncherView;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import static com.shenganyuan.smac.common.Config.APP_CARD_PATH_PICTURE_COMPRESS;

/**
 * @author Damon.Han
 */
public class IndexActivity extends Activity {

    private RxPermissions permissions;
    private ConfirmDialog confirmDialog;
    private String appName;
    private Map<String, Permission> allNeadPermissions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!isTaskRoot()) {
            finish();
            return;
        }
        appName = getResources().getString(R.string.app_name);
        setContentView(R.layout.act_index);
        LauncherView launcherView = findViewById(R.id.load_view);
        launcherView.post(new Runnable() {
            @Override
            public void run() {
                launcherView.start();
            }
        });
        launcherView.postDelayed(new Runnable() {
            @Override
            public void run() {
                getPermission();
            }
        }, 3000);
    }

    private void getPermission() {
        if (allNeadPermissions == null) {
            allNeadPermissions = new HashMap<>();
        }
        if (permissions == null) {
            permissions = new RxPermissions(this);
        }
        permissions
                .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE)
                .subscribe(permission -> {
                    allNeadPermissions.put(permission.name, permission);
                    //全部权限请求完毕
                    if (allNeadPermissions.size() == 2) {
                        Permission externalPermission = allNeadPermissions.get(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                        Permission readPhonePermission = allNeadPermissions.get(Manifest.permission.READ_PHONE_STATE);
                        if (externalPermission.granted && readPhonePermission.granted) {
                            initApp();
                            forwardToAct();
                        } else {
                            allNeadPermissions.clear();
                            Permission deniedPermission = !externalPermission.granted ? externalPermission : readPhonePermission;
                            showConfirmDialog(deniedPermission, !deniedPermission.shouldShowRequestPermissionRationale);
                        }
                    }
                });
    }

    /**
     * 在获取权限的情况下做一些初始化工作
     */
    private void initApp() {
        File file = new File(APP_CARD_PATH_PICTURE_COMPRESS);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    private void showConfirmDialog(Permission permission, boolean gotoSet) {
        if (confirmDialog == null) {
            confirmDialog = new ConfirmDialog(this);
            confirmDialog.setCanceledOnTouchOutside(false);
            confirmDialog.setCancelable(false);
            confirmDialog.setMessage("我们需要这些权限，为你提供服务;否则你将无法使用" + appName);
            confirmDialog.setNevigateButton("取消", view -> {
                confirmDialog.dismiss();
                IndexActivity.this.finish();
            });
        }

        if (permission != null && permission.name.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            confirmDialog.setMessage("我们需要获取存储空间权限，为你存储个人信息；否则你将无法使用" + appName);
        }

        if (permission != null && permission.name.equals(Manifest.permission.READ_PHONE_STATE)) {
            confirmDialog.setMessage("我们需要获取设备信息，为你进行设备识别；否则你将无法使用" + appName);
        }
        if (gotoSet) {
            confirmDialog.setPositiveButton("去设置", view -> {
                confirmDialog.dismiss();
                Intent localIntent = new Intent();
                localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", getPackageName(), null));
                startActivity(localIntent);
                IndexActivity.this.finish();
            });

        } else {
            confirmDialog.setPositiveButton("确定", view -> {
                confirmDialog.dismiss();
                getPermission();
            });
        }
        confirmDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (confirmDialog != null) {
            confirmDialog.dismiss();
            confirmDialog = null;
        }

    }

    /**
     * 根据是否初次安装选择跳转页面
     */
    private void forwardToAct() {
        getWindow().getDecorView().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (AnyPref.getDefault().getBoolean(Config.PrefKey.KEY_APP_FIRST_START, true)) {
                    Intent intent = new Intent();
                    intent.setClass(getApplicationContext(), FrontPageActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    //自动登录过程
                    APILoginParam apiLoginParam = App.getUserLoginPara();
                    if (TextUtils.isEmpty(apiLoginParam.name) || TextUtils.isEmpty(apiLoginParam.password)) {
                        gotoLogin();
                    } else {
                        loginCall(apiLoginParam.name, apiLoginParam.password);
                    }
                }
            }
        }, 2000);
    }

    /**
     * 登录请求
     *
     * @param username
     * @param pass
     */
    private void loginCall(String username, String pass) {
        ViseHttp.RETROFIT().create(Api.class).login(username, pass)
                .compose(RxUtil.rxSchedulerHelper())
                .subscribe(new ApiCallbackSubscriber<>(new ACallback<ApiLoginUser>() {
                    @Override
                    public void onSuccess(ApiLoginUser apiUser) {
                        try {
                            if (apiUser != null) {
                                if ("true".equalsIgnoreCase(apiUser.getResult())) {
                                    Intent intent = new Intent();
                                    intent.putExtra("data", apiUser.getDjuser());
                                    App.setCurrentUserAndToken(apiUser.getDjuser(), apiUser.getAccess_token());
                                    intent.setClass(IndexActivity.this, MainActivity.class);
                                    startActivity(intent);
                                    AnyPref.getDefault().putBoolean(Config.PrefKey.KEY_APP_FIRST_START, false);
                                    finish();
                                } else {
                                    ToastUtils.showToast(IndexActivity.this, apiUser.getMessage());
                                    gotoLogin();
                                }
                            } else {
                                ToastUtils.showToast(IndexActivity.this, "登录失败");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            ToastUtils.showToast(IndexActivity.this, "登录失败");
                            gotoLogin();
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        ToastUtils.showToast(IndexActivity.this, "自动登录失败，请重新登录");
                        gotoLogin();
                    }
                }));

    }

    /**
     *
     */
    private void gotoLogin() {
        Intent intent = new Intent();
        intent.setClass(IndexActivity.this, ActLogin.class);
        startActivity(intent);
        finish();
    }
}